package org.editor.util;

import org.editor.entity.Blog;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author zqx
 * @Date 2023-12-14
 */
public class HtmlUtils {

    public static final String TEMPLATE_FILE = "blog.html";

    public static void publish(Blog blog, String fromFile,String toFile) {
        Map<String, String> data = new HashMap<>();
        data.put("page_title", blog.getTitle());
        data.put("author", blog.getAuthor());
        data.put("content", blog.getContent());

        try {
            String templateContent = readTemplateFile(fromFile);
            String generatedHtml = generateHtml(templateContent, data);
            saveHtmlFile(generatedHtml, toFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 读取模板文件内容
     *
     * @param filePath
     * @return
     * @throws IOException
     */
    private static String readTemplateFile(String filePath) throws IOException {
        Path path = Paths.get(filePath);
        return new String(Files.readAllBytes(path));
    }

    /**
     * 生成 HTML 文档内容
     * @param templateContent
     * @param data
     * @return
     */
    private static String generateHtml(String templateContent, Map<String, String> data) {
        for (Map.Entry<String, String> entry : data.entrySet()) {
            templateContent = templateContent.replace("{{ " + entry.getKey() + " }}", entry.getValue());
        }
        return templateContent;
    }

    /**
     * 创建 HTML 文档
     * @param htmlContent
     * @param outputPath
     * @throws IOException
     */
    private static void saveHtmlFile(String htmlContent, String outputPath) throws IOException {
        Path path = Paths.get(outputPath);
        Files.write(path, htmlContent.getBytes());
    }
}
